package com.Xht.www.dao;

import com.Xht.www.po.UserBrowsingHistoryPO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserBrowsingHistoryDAO extends BaseDAO {
    // 关闭资源的私有方法
    private void closeResources(ResultSet rs, PreparedStatement stmt, Connection conn) {
        try {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            releaseConnection(conn); // 使用BaseDAO的releaseConnection方法释放连接
        } catch (SQLException e) {
            System.err.println("关闭资源失败: " + e.getMessage());
        }
    }

    // 插入用户浏览历史记录
    public boolean insertBrowsingHistory(UserBrowsingHistoryPO history) throws SQLException {
        Connection conn = null;
        PreparedStatement stmt = null;

        try {
            conn = getConnection();
            String sql = "INSERT INTO user_browsing_history (user_id, merchant_id, merchant_name, browsing_time) " +
                    "VALUES (?, ?, ?, ?)";
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, history.getUserId());
            stmt.setInt(2, history.getMerchantId());
            stmt.setString(3, history.getMerchantName());
            stmt.setTimestamp(4, history.getBrowsingTime());

            stmt.executeUpdate();
        } finally {
            closeResources(null, stmt, conn);
        }
        return false;
    }

    // 根据用户ID查询浏览历史
    public List<UserBrowsingHistoryPO> getBrowsingHistoryByUserId(Integer userId) throws SQLException {
        List<UserBrowsingHistoryPO> historyList = new ArrayList<>();
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try {
            conn = getConnection();
            String sql = "SELECT * FROM user_browsing_history WHERE user_id = ? ORDER BY browsing_time DESC";
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, userId);
            rs = stmt.executeQuery();

            while (rs.next()) {
                UserBrowsingHistoryPO history = new UserBrowsingHistoryPO();
                history.setBrowsingId(rs.getInt("browsing_id"));
                history.setUserId(rs.getInt("user_id"));
                history.setMerchantId(rs.getInt("merchant_id"));
                history.setMerchantName(rs.getString("merchant_name"));
                history.setBrowsingTime(rs.getTimestamp("browsing_time"));
                historyList.add(history);
            }
        } finally {
            closeResources(rs, stmt, conn);
        }

        return historyList;
    }
}